import TheUpload from '@/components/Upload';
import { updateReport } from '@/services/goods/report';
import { ModalForm, ProFormSelect, ProFormText } from '@ant-design/pro-components';
import { useDispatch, useSelector } from '@umijs/max';
import { Form, message } from 'antd';
import { useRef } from 'react';
import TableUp from '../TableWithUpload';

export default ({ actionRef }) => {
  const dispatch = useDispatch();
  const formRef = useRef();
  const { qualityreport } = useSelector((state) => state);
  const { addOpen, drawerParams } = qualityreport;
  const update = (data) => {
    dispatch({
      type: 'qualityreport/updateState',
      payload: data,
    });
  };

  return (
    <>
      <ModalForm
        title="编辑质检报告"
        open={addOpen}
        formRef={formRef}
        labelCol={{ span: 3 }}
        wrapperCol={{ span: 18 }}
        layout="horizontal"
        modalProps={{
          destroyOnClose: true,
          width: 1000,
          centered: true,
          afterOpenChange: (open) => {
            if (open) {
              formRef?.current?.setFieldsValue({
                id: drawerParams?.id,
                spuCode: drawerParams?.spuCode,
                skipItemId: drawerParams?.itemDto?.id,
                qualityName: drawerParams?.qualityName,
                qualityImage: [{ url: drawerParams?.qualityImage }] || [],
                qualityReportVo:
                  drawerParams?.qualityReportDtoList?.map((item) => ({
                    tableId: item?.id,
                    ...item,
                    qualityImageList: item?.qualityImageList?.map((i) => ({ url: i })),
                  })) || [],
              });
            }
          },
        }}
        onFinish={async (value) => {
          const { qualityImage, qualityReportVo, ...others } = value;
          const obj = {
            id: drawerParams?.id,
            spuCode: drawerParams?.spuCode,
            qualityImage: qualityImage?.[0]?.url,
            ...others,
          };
          const arr = [];
          let toclosed = true;
          qualityReportVo.forEach(({ tableId, ...itemOthers }) => {
            if (!itemOthers?.qualityDate) {
              toclosed = toclosed && false;
            } else {
              if (itemOthers?.id) {
                arr.push({
                  ...itemOthers,
                  qualityImageList: itemOthers?.qualityImageList?.map((i) => i.url),
                });
              } else {
                arr.push({
                  ...itemOthers,
                  spuCode: drawerParams?.spuCode,
                  qualityImageList: itemOthers?.qualityImageList?.map((i) => i.url),
                });
              }
            }
          });

          if (!toclosed) {
            message.success('质检日期不能为空');
            return false;
          }

          obj.qualityReportVo = arr;

          const newArr = drawerParams?.qualityReportDtoList?.filter((item) =>
            arr.some((i) => i?.id !== item?.id),
          );
          if (newArr?.length > 0) {
            obj.ids = newArr.map((i) => i?.id);
          }

          const data = await updateReport({ ...obj });
          if (data?.code === 200) {
            message.success('提交成功');
            update({
              drawerParams: {},
              addOpen: false,
            });
            return true;
          } else {
            return false;
          }
        }}
        onOpenChange={(open) => {
          if (!open) {
            update({
              drawerParams: {},
            });
            actionRef.current?.reload();
          }
          update({
            addOpen: open,
          });
        }}
      >
        <ProFormSelect
          name="skipItemId"
          label="跳转商品"
          options={drawerParams?.itemDtoList?.map((item) => ({
            label: item?.itemName,
            value: item?.id,
            mainGraph: item?.mainGraph,
          }))}
          placeholder="请选择商品"
          fieldProps={{
            onSelect: (value, option) => {
              formRef?.current?.setFieldsValue({
                qualityName: option?.label,
                qualityImage: [{ url: option?.mainGraph }] || [],
              });
            },
          }}
          rules={[{ required: true }]}
        />
        <ProFormText
          name="qualityName"
          label="质检名称"
          required
          rules={[{ required: true, message: '质检名称不能为空' }]}
          placeholder="请输入质检名称"
          fieldProps={{
            maxLength: 10,
          }}
        />
        <Form.Item name="qualityImage" label="质检主图" rules={[{ required: true }]}>
          <TheUpload
            listType="picture-card"
            maxCount={1}
            limitSize={5}
            // multiple={true}
            accept=".png, .jpg, .jpeg"
            warn="图片支持PNG、JPG、JPEG格式，大小不超过5MB，宽高比例为1:1"
          />
        </Form.Item>

        <Form.Item
          label="质检报告"
          name="qualityReportVo"
          required
          rules={[{ required: true, message: '质检报告不能为空' }]}
          labelCol={{ span: 3 }}
          wrapperCol={{ span: 25 }}
        >
          <TableUp />
        </Form.Item>
      </ModalForm>
    </>
  );
};
